package com.mck.utils;

import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @version 1.0.0
 * @Author mck
 * @Date 2025/4/23 下午1:10
 * @注释
 */

@Slf4j
public class IpLocationUtil {

    private static Searcher searcher;
    @PostConstruct  // 初始化searcher
    public void init() throws IOException {
        ClassPathResource resource = new ClassPathResource("ipdb/ip2region.xdb");
        byte[] bytes = Files.readAllBytes(Paths.get(resource.getURI()));
        searcher = Searcher.newWithBuffer(bytes);
    }

    /**
     * 获取客户端IP
     */
    public static String getIp(HttpServletRequest request) {
        String ip = null;

        // 检查多级代理的X-Forwarded-For，取第一个有效IP
        String[] headers = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
        for (String header : headers) {
            ip = request.getHeader(header);
            log.info("请求的IP地址：{}", ip);
            if (isValidIp(ip)) {
                // 处理多级代理的情况（取第一个非unknown的IP）
                int index = ip.indexOf(',');
                if (index != -1) {
                    ip = ip.substring(0, index).trim();
                }
                break;
            }
        }
        // 直接获取远程地址
        if (!isValidIp(ip)) {
            ip = request.getRemoteAddr();
        }
        // 规范化IPv6本地地址
        if ("0:0:0:0:0:0:0:1".equals(ip) || "::1".equals(ip)) {
            ip = "127.0.0.1";
        }
        return ip;
    }
    /**
     * 验证IP地址字符串是否有效
     *
     * @param ip 待验证的IP地址字符串
     * @return 当满足以下所有条件时返回true：
     *         1. ip不为null
     *         2. ip不是空字符串
     *         3. ip不等于"unknown"（不区分大小写）
     *         否则返回false
     */
    private static boolean isValidIp(String ip) {
        return ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip);
    }

    /**
     * 根据IP地址获取地址信息
     */
    public static String getAddress(String ip) {
        try {
            if(ip.equals( "127.0.0.1")) {
                return "本地";
            }

            String result = searcher.search(ip);
            String[] parts = result.split("\\|");
            return parts[2] + parts[4]; // 返回省和县
        } catch (Exception e) {
            return "未知地区";
        }
    }
}
